import numeral from 'numeral'
import { join, compact, map, isNull, isUndefined } from 'lodash'
import type { LogEntry } from '@/components/types'
import { ElMessageBox, ElMessage } from 'element-plus'

export const formatPercent = (number: number, format: string = '0.00%') => {
  return numeral(number).format(format)
}

export const getColorByCharCode = (val: string) => {
  const hash = val.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0)
  const hue = hash % 360
  return `hsl(${hue}, 70%, 50%)`
}

export function clearState(state) {
  Object.keys(state).forEach(key => {
    delete state[key] // Vue 3 支持通过 delete 触发响应式更新
  })
}

const getRandomId = () => {
  return Math.floor(Math.random() * 100) + 1
}

export const transformLogData = (logs: any[]): LogEntry[] => {
  return map(logs, (log: any) => ({
    id: getRandomId(),
    timestamp: log.log_date,
    level: log.log_level,
    originLevel: log.origin_log_level,
    type: log.log_type,
    sourceIp: log.src_ip,
    targetIp: log.dst_ip,
    agentIp: log.agent_ip,
    message: log.message,
    tags: log.tags,
    raw: log.raw,
  }))
}

export const checkDuplicateCondition = (
  existingItems: Array<{ id: number; name: string }>,
  newItem: { id: number | null; name: string }
): boolean => {
  return existingItems.some(item => {
    return (
      item.name === newItem.name &&
      (isNull(newItem.id) || isUndefined(newItem.id) || item.id !== newItem.id)
    )
  })
}

export const showConfirm = async (
  message: string,
  confirmCallback: () => Promise<void> | void,
  title: string = '告警'
) => {
  try {
    await ElMessageBox.confirm(message, title, {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await confirmCallback()
  } catch (err) {
    console.log('user canceled confirm:', err)
    // 用户取消了操作
  }
}

export const showConfirmDelete = async (
  target: string,
  confirmCallback: () => Promise<void> | void,
  title: string = '告警'
) => {
  try {
    await ElMessageBox.confirm(`确认删除"${target}"吗`, title, {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await confirmCallback()
  } catch (err) {
    console.log('user canceled confirm:', err)
    // 用户取消了操作
  }
}

export const showAlert = (message: string) => {
  ElMessageBox.alert(message, '提示', {
    confirmButtonText: '确定',
  })
}

export const showSuccessSaveMessage = (target: string | undefined) => {
  ElMessage.success(
    join(compact([target ? `"${target}"` : null, '保存成功']), '')
  )
}
export const showSuccessDeleteMessage = (target: string | undefined) => {
  ElMessage.success(
    join(compact([target ? `"${target}"` : null, '删除成功']), '')
  )
}
